new Vue({
    el: '#app',
    data() {
        return {
            id: '',
            form: {
                Remain_Quantity: 0,
                Start_Quantity: 0,
                Unit_Quantity: 0
            },//订单数据
            formData: {
                Amount: '0',
                Quantity: 0,
                Detailed_Address: '',
                CountyNumber: '',
                ProvinceNumber: '',
                CityNumber: '',
                Enterprise_Info_SerialNumber: getCookie('enterprise')
            },//提交数据
            trading: [],// 付款类型
            transport_method: [], // 运输方式
            shipment_method: [], // 装运方式
            payment_method: [], // 付款方式
            staged_payment: [], // 付款阶段
            city: [],
            loading: false,
        }
    },
    beforeCreate() {
        function setRem() {
            const designWidth = 750; // 设计稿宽度（rpx）
            const maxWidth = 540; // 可选：限制最大宽度（如手机端常见值）
            const screenWidth = Math.min(window.innerWidth, maxWidth);
            const scale = screenWidth / designWidth;
            document.documentElement.style.fontSize = scale + 'px';
        }
        setRem();//1rem = 0.5px 对标小程序在 375px 宽的屏幕上，1rpx = 0.5px（因为 750rpx / 375px = 2）
    },
    mounted() {
        let URL = window.location.href;
        this.id = getQueryObject(URL, 'id');
        this.init();
    },
    methods: {
        async init(callback) {
            const [res1, res2, res3, res4, res5, res6, res7] = await Promise.allSettled([
                generalApi.generalQueryByTableNameWithOriginal({
                    Data: 'supply_unitprice',
                    Condition: `Supply_Unit_Price_SerialNumber='${this.id}'`,
                }),
                generalApi.generalQueryBySQLSerialNumber({
                    SQLSerialNumber: 'm_payment_method_supply',
                    Condition: utf8ToBase64(this.id),
                }),
                generalApi.generalQueryBySQLSerialNumber({
                    SQLSerialNumber: 'm_shipment_method_supply',
                    Condition: utf8ToBase64(this.id),
                }),
                generalApi.generalQueryBySQLSerialNumber({
                    SQLSerialNumber: 'm_transport_method_supply',
                    Condition: utf8ToBase64(this.id),
                }),
                generalApi.generalQueryBySQLSerialNumber({
                    SQLSerialNumber: 'm_trading_supply',
                    Condition: utf8ToBase64(this.id),
                }),
                generalApi.generalFilePath('dtree.json'),
                generalApi.generalQueryByTableName({
                    Data: 'supply_unitprice_staged_payment',
                    Condition: `Supply_Unit_Price_SerialNumber='${this.id}'`,
                }),
            ]);
            if (res1.status == 'fulfilled' && res1.value.length == 1) {
                this.form = res1.value[0];
                this.formData.Quantity = res1.value[0].Start_Quantity;
                this.formData.Supply_Unit_Price_SerialNumber = this.id;
                this.changeQuantity(this.formData.Quantity);
            }
            if (res2.status == 'fulfilled') {
                this.payment_method = res2.value;
            }
            if (res3.status == 'fulfilled') {
                this.shipment_method = res3.value;
            }
            if (res4.status == 'fulfilled') {
                this.transport_method = res4.value;
            }
            if (res5.status == 'fulfilled') {
                this.trading = res5.value;
            }
            if (res6.status == 'fulfilled') {
                this.city = res6.value;
            }
            if (res7.status == 'fulfilled') {
                this.staged_payment = res7.value;
            }
            callback ? callback() : null;
        },
        changeCity(val) {
            this.formData.ProvinceNumber = val ? (val.substring(0, 2) + '0000') : '';
            this.formData.CityNumber = val ? (val.substring(0, 4) + '00') : '';
            this.formData.Detailed_Address = '';
        },
        changeQuantity(val) {
            this.formData.Amount = accMul(val, this.form.Unit_Price);
            this.formData.Remain_Amount = accMul(val, this.form.Unit_Price);
            this.formData.Unamount = accMul(val, this.form.Unit_Price);
            this.formData.Undelivery_Quantity = val;
            this.formData.Unreceipt_Quantity = val;
        },
        async handleSubmit() {// 申请
            if (this.loading) return
            // 校验
            const validationRules = [
                { key: 'Trading_SerialNumber', message: '请选择付款类型' },
                { key: 'Payment_Method_SerialNumber', message: '请选择支付方式' },
                { key: 'Shipment_Method_SerialNumber', message: '请选择装运方式' },
                { key: 'Transport_Method_SerialNumber', message: '请选择运输方式' },
                { key: 'Contacts', message: '请输入联系人' },
                { key: 'Contacts_Phone', message: '请输入联系电话' },
                { key: 'CountyNumber', message: '请选择收货地址' },
                { key: 'Detailed_Address', message: '请输入详细地址' },
            ];
            for (const rule of validationRules) {
                if (!this.formData[rule.key]) {
                    this.$showToast({ title: rule.message });
                    return; // 终止执行
                }
            }
            this.loading = true;

            // 提交
            const supply_unitprice = deepClone(this.form);

            // 一致性校验：扣减前校验剩余量是否足够
            const reqQty = Number(this.formData.Quantity || 0);
            const remainQty = Number(supply_unitprice.Remain_Quantity || 0);
            if (isNaN(reqQty) || reqQty <= 0) {
                this.$showToast({ title: '交易数量无效' });
                this.loading = false;
                return;
            }
            if (remainQty < reqQty) {
                this.$showToast({ title: '剩余量不足，无法提交申请' });
                this.loading = false;
                return;
            }

            supply_unitprice.Remain_Quantity = accSub(supply_unitprice.Remain_Quantity, this.formData.Quantity);
            supply_unitprice.Sales_Quantity = accAdd(supply_unitprice.Sales_Quantity, this.formData.Quantity);

            let supply_order_paystages = [];
            // if (this.formData.Trading_SerialNumber == '0') {// 全款
            //     supply_order_paystages.push({
            //         ...this.staged_payment.filter(i => i.Percent == '100'),
            //         Trading_Amount:this.formData.Amount,
            //         Remain_Amount:this.formData.Amount,
            //         Unamount:this.formData.Amount,
            //         Enterprise_Info_SerialNumber: getCookie('enterprise')
            //     })
            // } else { //分期
                let countMoney = 0;//计算已分配金额
                supply_order_paystages = this.staged_payment.map((item, index) => {
                    // 计算每阶段金额
                    let Trading_Amount = 0;
                    if (index == this.staged_payment.length - 1) { // 最后1个节点 总 - 已分配
                        Trading_Amount = accSub(this.formData.Amount, countMoney);
                    } else { // 剩下的节点  总 * 百分比 保留两位
                        Trading_Amount = parseInt(accMul(this.formData.Amount, item.Percent) / 100);
                        countMoney = accAdd(countMoney, Trading_Amount);
                    }
                    // 返回值
                    return {
                        ...item,
                        Trading_Amount,
                        Remain_Amount: Trading_Amount,
                        Unamount: Trading_Amount,
                        Enterprise_Info_SerialNumber: getCookie('enterprise')
                    }
                })
            // }

            this.formData.Children = { supply_order_paystages };

            const lJSONObject_DataSet = {
                Add: { supply_order: [this.formData] },
                Modify: { supply_unitprice: [supply_unitprice] }
            }

            let Operation_Main = JSON.stringify(deepClone(lJSONObject_DataSet));
            lJSONObject_DataSet['Add']['base_operation_log'] = [{
                Operation_Type: '1', //客户端
                Operation_Path: getRelativePath(),
                Operation_Description: '供应大厅摘牌',
                Operation_Main,
                Operation_Interface: "generalSaveByRequestBody",
                Operation_IP: getIpAddress()
            }]

            try {
                const res = await generalApi.generalSaveByRequestBody({
                    Data: lJSONObject_DataSet
                })

                if (res.Status == "success") {
                    this.$showToast({ title: "提交成功" });
                    window.location.href = './result.html';
                } else {
                    this.$showToast({ title: "提交失败，请重试！" });
                }

            } catch (error) {


            }

        }
    },
})
